package com.example.pt.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT拦截器，用于验证请求中的JWT令牌
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        // 如果 Authorization 头为空，尝试从 token 头获取
        if (token == null || token.isEmpty()) {
            token = request.getHeader("token");
        }

        // 如果没有token，返回401未授权
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "未授权：缺少token");
            response.getWriter().write(errorResponse.toString());
            return false;
        }
        
        // 如果token前缀是Bearer，去掉前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            // 验证token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            if (decodedJWT == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("status", "error");
                errorResponse.put("message", "未授权：无效token");
                response.getWriter().write(errorResponse.toString());
                return false;
            }
            
            // 将解析出的用户信息存入request，方便后续使用
            request.setAttribute("usertype", decodedJWT.getClaim("usertype").asInt());
            request.setAttribute("uid", decodedJWT.getClaim("uid").asInt());
            
            return true;
            
        } catch (TokenExpiredException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "未授权：token已过期");
            response.getWriter().write(errorResponse.toString());
            return false;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", "未授权：token验证失败");
            response.getWriter().write(errorResponse.toString());
            return false;
        }
    }
} 